package tools

import (
	"path"
	"reflect"

	"github.com/tealeg/xlsx"
)

// 校验 .xlsx
func CheckExcleName(filepath string) bool {
	fileExt := path.Ext(filepath)
	return fileExt == ".xlsx"
}

// 读取文件
func ReadExcle(filepath string) [][][]string {
	out, err := xlsx.FileToSlice(filepath)
	if err != nil {
		panic(err.Error())
	}
	return out
}

// 校验表头
func CheckHeader(out [][][]string, obj interface{}) bool {
	typeof := reflect.TypeOf(obj)
	for i := 0; i < typeof.NumField(); i++ { //循环结构体内字段的数量
		//获取结构体内索引为i的字段值
		if typeof.Field(i).Tag.Get("is_header") == "true" && out[0][0][i] != typeof.Field(i).Tag.Get("header") {
			return false
		}
	}
	return true
}

// 导出表格
func SaveExcle(filename string, sheetName string, header []string, values []interface{}) (string, error) {
	f := xlsx.NewFile()
	sheet, _ := f.AddSheet(sheetName)

	if len(header) != 0 {
		row := sheet.AddRow()
		for _, v := range header {
			row.AddCell().SetValue(v)

		}
	}

	for _, v := range values {
		row := sheet.AddRow()
		t := reflect.ValueOf(v)
		k := reflect.TypeOf(v)
		for i := 0; i < t.NumField(); i++ {
			if k.Field(i).Tag.Get("write") == "false" {
				continue
			}
			row.AddCell().SetValue(t.Field(i))
		}

	}
	if err := f.Save(filename); err != nil {
		return "", nil
	}

	return filename, nil
}

// 导出表格, 用于导出多个sheet
func SaveSheetsExcle(filename string, sheetNames []string, header []string, values [][]interface{}) (string, error) {
	f := xlsx.NewFile()
	for i, sheetName := range sheetNames {
		sheet, _ := f.AddSheet(sheetName)

		if len(header) != 0 {
			row := sheet.AddRow()
			for _, v := range header {
				row.AddCell().SetValue(v)

			}
		}
		value := values[i]
		for _, v := range value {
			row := sheet.AddRow()
			t := reflect.ValueOf(v)
			k := reflect.TypeOf(v)
			for i := 0; i < t.NumField(); i++ {
				if k.Field(i).Tag.Get("write") == "false" {
					continue
				}
				row.AddCell().SetValue(t.Field(i))
			}

		}
		if err := f.Save(filename); err != nil {
			return "", err
		}
	}
	return filename, nil
}

// 导出表格, 用于导出多个sheet
func SaveMultSheetsExcle(filename string, sheetNames []string, headerMap map[int][]string, values [][][]interface{}) (string, error) {
	f := xlsx.NewFile()
	for i, sheetName := range sheetNames {
		sheet, _ := f.AddSheet(sheetName)
		var header []string
		if h := headerMap[i]; len(h) != 0 {
			header = headerMap[i]
		}
		if len(header) != 0 {
			row := sheet.AddRow()
			for _, v := range header {
				row.AddCell().SetValue(v)
			}
		}
		vs := values[i]
		for i := 0; i < len(vs); i++ {
			value := vs[i]
			for _, v := range value {
				row := sheet.AddRow()
				t := reflect.ValueOf(v)
				k := reflect.TypeOf(v)
				for i := 0; i < t.NumField(); i++ {
					if k.Field(i).Tag.Get("write") == "false" {
						continue
					}
					row.AddCell().SetValue(t.Field(i))
				}

			}
		}
		if err := f.Save(filename); err != nil {
			return "", err
		}

	}
	return filename, nil
}
